package cao.oschina.function.multiple.news;

import android.content.Intent;
import android.view.View;
import android.webkit.WebView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import cao.oschina.R;
import cao.oschina.activity.ToolBarActivity;
import cao.oschina.api.URLs;
import cao.oschina.bean.NewsDetailModal;
import cao.oschina.bean.Relative;
import cao.oschina.util.WebViewHelper;
import hd.util.ToastUtil;
import hd.util.ViewAnimation;
import hd.util.app.NetworkType;
import hd.util.http.HttpClient;
import hd.util.http.HttpRequestListener;
import hd.util.http.HttpResponse;
import hd.util.xml.XmlParser;

/**
 * 详细新闻
 * <p/>
 * Created by Haidy on 15/3/29.
 */
public class NewsDetail extends ToolBarActivity implements ViewAnimation.OnAnimationListener {

    private WebView webView;
    private LinearLayout toolsView;
    private LinearLayout editToolsView;
    private EditText editText;
    private TextView commentCountView;
    private ImageButton collectButton;

    private String newsId;              //新闻id

    private boolean isToolsType = true; //tools状态

    private ViewAnimation animation;

    /**
     * 初始化界面
     */
    @Override
    protected void initView() {
        configBack();
        setTitle("详细新闻");
        setBody(R.layout.news_detail_view);
        webView = (WebView) findViewById(R.id.web_view);
        webView.getSettings().setSupportZoom(true);
        webView.getSettings().setDefaultFontSize(20);

        toolsView = (LinearLayout) findViewById(R.id.toolbar);
        editToolsView = (LinearLayout) findViewById(R.id.edit_tools_view);
        editText = (EditText) findViewById(R.id.comment_edit);
        commentCountView = (TextView) findViewById(R.id.comment_count);

        findViewById(R.id.edit_option).setOnClickListener(clickListener);
        findViewById(R.id.tools_option).setOnClickListener(clickListener);
        findViewById(R.id.comment_btn).setOnClickListener(clickListener);
        findViewById(R.id.edit_btn).setOnClickListener(clickListener);
        findViewById(R.id.share_btn).setOnClickListener(clickListener);
        collectButton = (ImageButton) findViewById(R.id.collect_btn);
        collectButton.setOnClickListener(clickListener);
    }

    /**
     * 初始化数据
     */
    @Override
    protected void initData() {
        animation = new ViewAnimation();
        animation.setDuration(150);
        animation.setOnAnimationListener(this);
        newsId = getIntent().getStringExtra("id");
        String commentCount = getIntent().getStringExtra("comment_count");
        if (commentCount != null && !commentCount.equals("0")) {
            commentCountView.setText(commentCount);
        } else {
            commentCountView.setVisibility(View.GONE);
        }
        loadNewsDetail();
    }

    /**
     * 获取详细新闻
     */
    private void loadNewsDetail() {
        isLoading = true;
        new HttpClient().httpGet(URLs.NEWS_DETAIL + "?id=" + newsId, new HttpRequestListener() {
            @Override
            public void success(HttpResponse response) {
                NewsDetailModal newsDetailModal = new XmlParser<NewsDetailModal>(response.text, NewsDetailModal.class).parserData("news");
                if (newsDetailModal != null) {
                    showDetail(newsDetailModal);
                } else {
                    ToastUtil.toastShort("新闻不存在");
                }
            }

            @Override
            public void failure(HttpResponse response) {
                ToastUtil.toastShort(response.info);
            }

            @Override
            public void end() {
                super.end();
                isLoading = false;
            }
        });
    }

    /**
     * 显示新闻信息
     *
     * @param modal 实体对象
     */
    private void showDetail(NewsDetailModal modal) {
        StringBuilder body = new StringBuilder(WebViewHelper.WEB_STYLE);
        body.append(modal.body);
        String str = body.toString();
        if (app.getNetworkType() == NetworkType.NETTYPE_WIFI || app.getConfig().isLoadImage()) {
            str = str.replaceAll("(<img[^>]*?)\\s+width\\s*=\\s*\\S+", "$1")
                    .replaceAll("(<img[^>]*?)\\s+height\\s*=\\s*\\S+", "$1").replaceAll("(<img[^>]+src=\")(\\S+)\"",
                            "$1$2\" onClick=\"javascript:mWebViewImageListener.onImageClick('$2')\"");//支持图片双击放大
        } else {
            str = str.replaceAll("<\\s*img\\s+([^>]*)\\s*>", "");
        }
        body.setLength(0);
        body = new StringBuilder(str);
        //更多相关软件
        if (modal.softwarename != null) {
            body.append(String.format("<div id='oschina_software' style='margin-top:8px;color:#FF0000;font-weight:bold'>更多关于:&nbsp;<a href='%s'>%s</a>&nbsp;的详细信息</div>", modal.softwarelink, modal.softwarename));
        }
        //相关资讯
        StringBuilder sb = new StringBuilder("");
        if (modal.relativies != null) {
            for (Relative relative : modal.relativies) {
                sb.append(String.format("<a href='%s' style='text-decoration:none'>%s</a><p/>", relative.rurl, relative.rtitle));
            }
            body.append(String.format("<p/><hr/><b>相关资讯</b><div><p/>%s</div>", sb.toString()));
        }
        body.append("<div style='margin-bottom: 40px'/>");
        webView.loadDataWithBaseURL(null, body.toString(), "text/html", "utf-8", null);

        //评论数
        if (modal.commentCount.equals("0")) {
            commentCountView.setVisibility(View.GONE);
        } else {
            commentCountView.setVisibility(View.VISIBLE);
            commentCountView.setText(modal.commentCount);
        }

        //是否收藏
        if (modal.favorite.equals("1")) {
            collectButton.setImageResource(R.drawable.ic_action_favor_on);
        }
    }

    /**
     * 点击事件监听
     */
    private View.OnClickListener clickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.edit_option://切换到编辑状态
                case R.id.tools_option://切换到tools状态
                    changeToolsType();
                    break;
                case R.id.comment_btn://切换到评论界面
                    openCommentList();
                    break;
                case R.id.edit_btn://编辑
                    isEdit = true;
                    changeToolsType();
                    break;
                case R.id.collect_btn://收藏

                    break;
                case R.id.share_btn://分享

                    break;
            }
        }
    };

    private boolean isEdit = false;
    private boolean startAnim = false;

    /**
     * 切换bottom tools bar和edit bar
     */
    private void changeToolsType() {
        startAnim = true;
        if (isToolsType) {
            animation.startAnimation(toolsView, 0, 0, 0, -toolsView.getHeight());
        } else {
            closeInputMethod();
            animation.startAnimation(editToolsView, 0, 0, 0, -editToolsView.getHeight());
        }
    }

    /**
     * 打开评论列表
     */
    private void openCommentList() {
        Intent intent = new Intent(getBaseContext(), Comment.class);
        intent.putExtra("id", newsId);
        startActivity(intent);
        activityPushAnim();
    }

    @Override
    public void onAnimationStart() {

    }

    @Override
    public void onScrollTo(int pixelX, int pixelY) {

    }

    @Override
    public void onAnimationStop() {
        if (startAnim) {
            if (isToolsType) {
                editToolsView.setVisibility(View.VISIBLE);
                toolsView.setVisibility(View.GONE);
                animation.startAnimation(editToolsView, 0, -editToolsView.getHeight(), 0, editToolsView.getHeight());
            } else {
                toolsView.setVisibility(View.VISIBLE);
                editToolsView.setVisibility(View.GONE);
                animation.startAnimation(toolsView, 0, -toolsView.getHeight(), 0, toolsView.getHeight());
            }
            isToolsType = !isToolsType;
            startAnim = false;
        } else {
            if (!isToolsType && isEdit) {
                openInputMethod(editText);
            }
            isEdit = false;
        }
    }
}
